package cn.supermaster.management.web.service.common.impl;

import cn.supermaster.management.common.configure.SMManagementConfiguration;
import cn.supermaster.management.common.configure.ServerConfiguration;
import cn.supermaster.management.common.constant.Constants;
import cn.supermaster.management.common.response.WebResponse;
import cn.supermaster.management.common.utils.TextUtils;
import cn.supermaster.management.common.utils.file.FileUploadUtils;
import cn.supermaster.management.common.utils.file.FileUtils;
import cn.supermaster.management.web.controller.common.CommonController;
import cn.supermaster.management.web.service.common.ICommonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: supermaster-management
 * @Package: cn.supermaster.management.web.service.common.impl
 * @ClassName: CommonServiceImpl
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2021/1/10 16:25
 * @Version: V1.0
 * @Copyright: 2021 www.super-bytecode.comn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Service
public class  CommonServiceImpl implements ICommonService {

    private  final Logger logger = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfiguration serverConfiguration;

    /**
     * @Description: [通用下载请求]
     * <p></P>
     * @Title: doFileDownload
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: request request请求对象
     * @Param: response response响应对象
     * @Param: fileName 文件名称
     * @Param: deleteFlag 删除标识
     * @Return: void
     */
    @Override
    public  void doFileDownload(HttpServletRequest request, HttpServletResponse response, String fileName, Boolean delete) {

        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(TextUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = SMManagementConfiguration.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            logger.error("下载文件失败", e);
        }
    }

    /**
     * @Description: [通用上传请求]
     * <p></P>
     * @Title: doUploadFile
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: file
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doUploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = SMManagementConfiguration.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfiguration.getUrl() + fileName;
            WebResponse ajax = WebResponse.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return WebResponse.failure(e.getMessage());
        }
    }

    /**
     * @Description: [本地资源通用下载]
     * <p></P>
     * @Title: doResourceDownload
     * @Author: Lance Ting
     * @Date: 2021-01-10
     * @Param: request
     * @Param: response
     * @Param: resource
     * @Return: void
     */
    @Override
    public  void doResourceDownload(HttpServletRequest request, HttpServletResponse response, String resource) {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(TextUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = SMManagementConfiguration.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + TextUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = TextUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            logger.error("下载文件失败", e);
        }
    }
}